﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Krilib.Control;
using Krilib.Data;
using Krilib;
using Krilib.Control.Surface;

namespace Wassrile.Controls
{
    public class Pictogram : MessageObject
    {
        public string code;

        public Image _cache;
        public Image cache
        {
            get { return _cache; }
            set
            {
                if (animate != null)
                {
                    ImageAnimator.StopAnimate(_cache, animate);
                    animate = null;
                }
                _cache = value;
                if (ImageAnimator.CanAnimate(_cache))
                {
                    animate = new EventHandler(FrameUpdated);
                    ImageAnimator.Animate(_cache, animate);
                }
            }
        }
        EventHandler animate = null;
        private void FrameUpdated(object sender, EventArgs e)
        {
            Bridge.MainForm.RefreshTLWeak();
        }

        public Pictogram(string cod)
            : base()
        {
            code = cod;
            cache = Core.PictogramResolver.GetPictogram(cod);
        }

        public override void Draw(Graphics g, CompositeDescriptor desc)
        {
            if (animate != null)
                ImageAnimator.UpdateFrames(_cache);
            int xp = desc.StartXPos + desc.LeftTop.X;
            int h = desc.LeftTop.Y;
            int c = 0;
            if (desc.Heights.Length > 1)
            {
                xp = desc.LeftTop.X;
                h = desc.Heights[0] + desc.LeftTop.Y;
                c++;
            }
            int yp = (int)Math.Ceiling((desc.Heights[c] - 16) / 2.0);
            g.DrawImage(cache, new Rectangle(xp, h + yp, 16, 16));
        }

        public override bool HitTest(Point position)
        { return false; }

        public override void Composite(Compositor compz)
        {
            compz.SetCurrentLineHeight(16);
            if (compz.ClientWidth - compz.CurrentXPosition < 16)
                compz.MoveNewLine();
            compz.CurrentXPosition += 16;
        }

        public override void Release() { }
    }
}
